const Koa = require('koa')
const KoaRouter = require('koa-router')
const KoaBodyParser = require('koa-bodyparser')
const cors = require('koa2-cors')
const mysql = require('./mysql.js')
const corsConfig = require('./cors.js')

const app = new Koa()
const router = new KoaRouter()

app.use(cors(corsConfig))
app.use(KoaBodyParser())
app.use(router.routes())
app.use(router.allowedMethods())

app.listen('3000', (err) => {
  if(err) console.log("koa 服务器启动失败")
  else console.log("koa 服务器启动成功，地址为http://localhost:3000")
})

router.post('/news', async (ctx, next) => {
  const type = ctx.request.body.type
  const query = `select * from news where article_type=${type} order by datetime desc;`
  let res = await mysql.allSqlAction(query)
  console.log(res)
  ctx.body = {
    res: res
  }
})

router.post('/newsdetail', async (ctx, next) => {
  const newsid = ctx.request.body.newsid
  const query = `select * from news where id=${newsid}`
  const res = await mysql.allSqlAction(query)
  console.log(res)
  ctx.body = {
    res: res
  }
})

router.post('/video', async (ctx, next) => {
  const video_type = ctx.request.body.video_type
  console.log(video_type)
  const query = `select * from video where video_type=${video_type}`
  const res = await mysql.allSqlAction(query)
  console.log(res)
  ctx.body = {
    res: res
  }
})

router.post('/video/changeVideoStatus', async (ctx, next) => {
  const videoChangeData = ctx.request.body
  console.log(videoChangeData)
  videoChangeData.likestatus = Number(videoChangeData.likestatus)
  const query = `UPDATE video SET likestatus=${videoChangeData.likestatus}, likecount=${videoChangeData.likecount} where id=${videoChangeData.video_id}`
  await mysql.allSqlAction(query)
  ctx.body = {
    res: null
  }
})

router.post('/post/getpost', async (ctx, next) => {
  const query = `select * from topic`
  const res = await mysql.allSqlAction(query)
  console.log(res)
  ctx.body = {
    res: res
  }
})

router.post('/post/sendpost', async (ctx, next) => {
  const post = ctx.request.body.post
  const date = new Date().toLocaleString()
  console.log(post)
  const query = `insert into topic (content, img_url, likecount, likestatus, publish_time) VALUES ('${post.content}', '${post.img_url}', 0, 0, '${date}')`
  await mysql.allSqlAction(query)
  ctx.body = {
    res: null
  }
})